package com.okilo.online.app.act

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.okilo.online.app.R
import com.okilo.online.app.apt.OkiloMainApt
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.databinding.OkiloActMainBinding
import com.okilo.online.app.dialog.OkiloUpdateDlog
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.fmt.OkiloTabHomeFmt
import com.okilo.online.app.fmt.OkiloTabMeFmt
import com.okilo.online.app.fmt.OkiloTabRepayFmt
import com.okilo.online.app.pet.OkiloConfigsPet
import com.okilo.online.app.pet.OkiloLibPet
import com.okilo.online.app.pet.OkiloLoanPet
import com.okilo.online.app.pet.view.IOkiloConfigs
import com.okilo.online.app.pet.view.IOkiloLoan
import com.okilo.online.app.tools.OkiloDateUtil
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.apt.OkiloOnItemChildClickListener
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.tools.helper.OkiloUpdateHp
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class OkiloMainAct: OkiloComAct(), IOkiloConfigs.IOkiloConfigProcess, IOkiloLoan.IOkiloRepay{
    lateinit var binding: OkiloActMainBinding

    //首页
    private var mainHomeFragment: OkiloTabHomeFmt? = null
    //待还款
    private var mainRepayFragment: OkiloTabRepayFmt? = null
    //个人中心
    private var mainMenuFragment: OkiloTabMeFmt? = null

    //获取配置
    private var okiloConfigPet: OkiloConfigsPet? = null
    //待还款信息
    private var okiloRepayPet: OkiloLoanPet? = null

    private var okiloMainTabApt: OkiloMainApt? = null
    private var selectedTabIndex = 0

    private var updateHelper: OkiloUpdateHp? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功

        } else {

        }
    }

    override var pageName: String = "Main_Page"

    //禁用埋点
    override val enablePageTrack: Boolean = false

    override fun createOkiloContentView(): View {
        binding = OkiloActMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeOkiloViews() {
        setBackExit(true)
        getTitleBarManager()
            .setRootBackgroundColor(getColor(R.color.okilo_color_ffeff1f3))
            .setTitleBarVisibility(View.VISIBLE)
            .setBackButtonVisibility(View.GONE)
            .setRightButtonVisibility(View.VISIBLE)
            .setTitleVisibility(View.GONE)
        OkiloTitleBarUtil.setStatusBarLightMode(this, true)
        initOkiloMainTabPageGridView()
        //移除流程接口数据
        OkiloSharedHp.dOkiloSharedData(OkiloSharedKey.SP_OKILO_PROCESS)
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
    }

    override fun loadOkiloData() {
        if (okiloConfigPet == null){
            okiloConfigPet = OkiloConfigsPet(this)
        }
        gOkiloMainTabPageList()

        //是否有新版本
        val isUpdate = OkiloConfigCustomerHp.iOkiloReleaseUpdate()
        if (isUpdate){
            sOkiloMainUpdateDialog()
        }
    }

    /**
     * 初始化Tab列表
     */
    private fun initOkiloMainTabPageGridView() {
        val layoutManager = GridLayoutManager(this, 3)
        binding.mainTabListView.layoutManager = layoutManager
        okiloMainTabApt = OkiloMainApt(binding.mainTabListView)
        binding.mainTabListView.adapter = okiloMainTabApt
        binding.mainTabListView.itemAnimator = DefaultItemAnimator()
        okiloMainTabApt?.setOnItemChildClickListener(OkiloOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.okiloMainItemLayout) {//切换item
                checkOkiloTabPage(position)
            }
        })
    }

    /**
     * 加载Tablist
     */
    private fun gOkiloMainTabPageList(){
        val tabIconNormalList = arrayListOf(R.mipmap.okilo_main_home_normal, R.mipmap.okilo_main_repayment_normal, R.mipmap.okilo_main_me_normal)
        val tabIconSelectedList = arrayListOf(R.mipmap.okilo_main_home_selected, R.mipmap.okilo_main_repayment_selected, R.mipmap.okilo_main_me_selected)
        val tabTitleList = arrayListOf(R.string.okilo_main_home, R.string.okilo_main_repayment, R.string.okilo_main_me)

        val tabList = arrayListOf<JSONObject>()
        //tab
        for (i in 0 until tabTitleList.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabNormalIcon", tabIconNormalList[i])
            tabObj.put("tabSelectedIcon", tabIconSelectedList[i])
            tabObj.put("tabTitle", getString(tabTitleList[i]))
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        okiloMainTabApt?.data = tabList
        checkOkiloTabPage(0)
    }

    /**
     * 切换page
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun checkOkiloTabPage(position: Int){
        selectedTabIndex = position
        okiloMainTabApt?.let {
            for (i in 0..< it.data.size){
                val item = it.getItem(i)
                item.put("isSelect", position == i)
            }
            it.notifyDataSetChanged()

            val item = it.getItem(position)
        }
        checkOkiloMainTabShowPage()
    }

    /**
     * 隐藏所有的页面
     */
    private fun hideOkiloAllTabPage() {
        mainHomeFragment?.let {
            getFragmentNavigator().hideFragment(it)
        }
        mainRepayFragment?.let {
            getFragmentNavigator().hideFragment(it)
        }
        mainMenuFragment?.let {
            getFragmentNavigator().hideFragment(it)
        }
    }

    /**
     * 检查首页显示内容
     */
    private fun checkOkiloMainTabShowPage(){
        when(selectedTabIndex){
            0 -> {//首页
                pageName = "Main_Page"
                sOkiloTabHomePage()
            }
            1 -> {//待还款
                pageName = "Repay_Page"
                sOkiloTabRepayPage()
            }
            else -> {//个人中心
                pageName = "UserCenter_Page"
                sOkiloTabUserCenterPage()
            }
        }
    }

    /**
     * 显示首页
     */
    private fun sOkiloTabHomePage(){
        hideOkiloAllTabPage()
        if (mainHomeFragment == null) {
            mainHomeFragment = OkiloTabHomeFmt()
        }
        mainHomeFragment?.let {
            if (it.isAdded) {
                getFragmentNavigator().showFragment(it)
            } else {
                getFragmentNavigator().addFragment(R.id.mainContentLayout, it)
                showOkiloLoading()
                lifecycleScope.launch {
                    delay(200)
                    okiloConfigPet?.gOkiloConfigProcessRequest(this@OkiloMainAct)
                }
            }
        }
    }

    /**
     * 待还款
     */
    private fun sOkiloTabRepayPage(){
        hideOkiloAllTabPage()
        if (mainRepayFragment == null) {
            mainRepayFragment = OkiloTabRepayFmt()
        }
        mainRepayFragment?.let {
            if (it.isAdded) {
                getFragmentNavigator().showFragment(it)
            } else {
                getFragmentNavigator().addFragment(R.id.mainContentLayout, it)
                showOkiloLoading()
                lifecycleScope.launch {
                    delay(200)
                    okiloConfigPet?.gOkiloConfigProcessRequest(this@OkiloMainAct)
                }
            }
        }
    }

    /**
     * 显示个人中心
     */
    private fun sOkiloTabUserCenterPage(){
        hideOkiloAllTabPage()
        if (mainMenuFragment == null) {
            mainMenuFragment = OkiloTabMeFmt()
        }
        mainMenuFragment?.let {
            if (it.isAdded) {
                getFragmentNavigator().showFragment(it)
            } else {
                getFragmentNavigator().addFragment(R.id.mainContentLayout, it)
            }
        }
    }

    /**
     * 需要校验手机号
     */
    fun sOkiloVerifyMobilePage() {
        //当前栈顶是 手机号校验页面 不重复跳转
        if (OkiloActStackManager.isCurrentActivity(OkiloVerifyMobileAct::class.java)){
            return
        }
        //是否是审核账号
        val isAdmin = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接不走校验
            return
        }
        OkiloVerifyMobileAct.Companion.start(this)
    }

    /**
     * 版本更新Dialog
     */
    private fun sOkiloMainUpdateDialog(){
        val lastShowTime = OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_UPDATE_VERSION_LAST_TIME)
        if (lastShowTime.isNotEmpty() && OkiloDateUtil.isSameDay(lastShowTime.toLong(),System.currentTimeMillis())){
            return
        }
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_UPDATE_VERSION_LAST_TIME,"${System.currentTimeMillis()}")
        val updateDialog = OkiloUpdateDlog(this, pageName, object : OkiloUpdateDlog.IDialogCallback {
                override fun onUpdateClick() {
                    try {
                        if (updateHelper == null) {
                            updateHelper = OkiloUpdateHp(
                                activity = this@OkiloMainAct,
                                forceUpdate = false,
                                updateLauncher
                            )
                        }
                        updateHelper?.checkAndStartUpdate { }
                    } catch (e: Exception) {

                    }
                }
            })
        updateDialog.show()
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        OkiloLog.i(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESH -> {//刷新流程
                okiloConfigPet?.gOkiloConfigProcessRequest(this)
            }
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED -> {//流程刷新完成
                val isRepay = OkiloConfigProcessHp.iOkiloApplyOrderRepay()
                if (isRepay){//待还款，直接刷新还款信息
                    if (okiloRepayPet == null){
                        okiloRepayPet = OkiloLoanPet(this)
                    }
                    okiloRepayPet?.gOkiloRepayInfoRequest(this)
                }
            }
            OkiloEventData.TYPE.OKILO_SHOW_HOME -> {//显示首页
                checkOkiloTabPage(0)
            }
            OkiloEventData.TYPE.OKILO_SHOW_REPAY -> {//待还款
                checkOkiloTabPage(1)
            }
            OkiloEventData.TYPE.OKILO_SYC_ALL_DEVICE -> {//上报所有设备数据
                OkiloLog.i(">>>>>>>>>>>>>>>>syc device all data ")
                //此通知只会在申贷完成之后发送
                OkiloLibPet.gOkiloDeviceInfoTypesRequest()
            }
            else -> {

            }
        }
    }

    /**
     * 获取流程配置完成
     */
    override fun sOkiloConfigProcessCallback() {
        if (OkiloConfigProcessHp.iOkiloCheckWhatsAppFlag() || OkiloConfigProcessHp.iOkiloCheckSmsFlag()){
            sOkiloVerifyMobilePage()
        }
    }

    /**
     * 获取待还款信息完成
     */
    override fun sOkiloLoadRepayInfo(data: JSONObject) {
        publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_REPAY_INFO_REFRESHED, data))
    }
}